package com.aocuploader;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import com.aocuploader.ImageUpload.ImageUploadTask;
import com.appbucks.sdk.AppBucksAPI;
import com.appbucks.sdk.AppBucksBanner;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class LoginPage extends Activity {
	private Button submitbutton;
    private EditText username;
    private EditText password;
    private ProgressDialog dialog;
    private AppBucksBanner banner;
    public static String imageauthor = "";
    public static String nama = "";
    public static String muka = "";

    public void connectivityMessage(String msg){
        Context context = getApplicationContext();
        Toast toast = Toast.makeText(context, "", Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setText(msg);
        toast.show();
   }
    
   
    public void onCreate(Bundle savedInstanceState) {
    	
    	AppBucksAPI.initialize(this, "AoC United Apps", 1710571783 , "7fe5e5b4-1883-4cb7-b77c-4879d5efcbcd", false , null, null); 
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loginpage);
        
        submitbutton = (Button) findViewById(R.id.btnKirim);
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        
        submitbutton.setFocusableInTouchMode(true);
        submitbutton.requestFocus();

        submitbutton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				if(username.getText().toString().equals("") || password.getText().toString().equals(""))
				{
					Toast.makeText(getApplicationContext(),
							"Isi Username ama Passwordnya dong :D", Toast.LENGTH_LONG).show();
				}
				else
				{
					 CheckConnectivity check = new CheckConnectivity();
				     Boolean conn = check.checkNow(getApplicationContext());
				     if(conn){
				          //run your normal code path here
				    	 //Toast.makeText(getApplicationContext(),
							//		"Terhubung gan",
								//	Toast.LENGTH_LONG).show();
				    	dialog = ProgressDialog.show(LoginPage.this, "Sedang konek ke server....",
										"Tunggu ye...", true);
							new LoginPageTask().execute();
				     }
				     else{
				          //Send a warning message to the user
				    	 Toast.makeText(getApplicationContext(),
									"Pastikan agan terhubung dengan internet",
									Toast.LENGTH_LONG).show();
				     }
				     
				}
			}
		});
        
        banner = (AppBucksBanner)findViewById(R.id.bannercoy); 
        banner.showAd(); 
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_login_page, menu);
        return true;
    }
    
    class LoginPageTask extends AsyncTask<Void, Void, String> {
		@Override
		protected String doInBackground(Void... unsued) {
			try {
				String sResponse = null;
				HttpClient httpClient = new DefaultHttpClient();
				HttpContext localContext = new BasicHttpContext();
				HttpPost httpPost = new HttpPost("http://aocunited.com/RemoteUpload/login");
				
				MultipartEntity entity = new MultipartEntity(
						HttpMultipartMode.BROWSER_COMPATIBLE);
				entity.addPart("username", new StringBody(username.getText()
						.toString()));
				entity.addPart("password", new StringBody(password.getText()
						.toString()));
				httpPost.setEntity(entity);
				HttpResponse response = httpClient.execute(httpPost,
						localContext);
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(
								response.getEntity().getContent(), "UTF-8"));

				sResponse = reader.readLine();
				return sResponse;
			} catch (Exception e) {
				if (dialog.isShowing())
					dialog.dismiss();
				Toast.makeText(getApplicationContext(),
						e.getMessage(),
						Toast.LENGTH_LONG).show();
				Log.e(e.getClass().getName(), e.getMessage(), e);
				return null;
			}

			// (null);
		}

		@Override
		protected void onProgressUpdate(Void... unsued) {

		}

		@Override
		protected void onPostExecute(String sResponse) {
			
			String[] temp;
			String delimiter = "&";
			  
			try {
				if (dialog.isShowing())
					dialog.dismiss();

				if (sResponse != null) {
					temp = sResponse.split("&");
					if(temp[0].equals("success"))
					{	
						imageauthor = temp[1];
						nama = username.getText().toString();
						muka = temp[2];
						Helper.username = nama;
						Helper.profpic = muka;
						Intent mainmenu = new Intent(getApplicationContext(),MainMenu.class);
						startActivity(mainmenu);
					}
					else
					{
						Toast.makeText(getApplicationContext(),
								sResponse,
								Toast.LENGTH_LONG).show();
					}
				}
			} catch (Exception e) {
				Toast.makeText(getApplicationContext(),
						e.getMessage(),
						Toast.LENGTH_LONG).show();
				Log.e(e.getClass().getName(), e.getMessage(), e);
			}
		}
	}
}
